package me.zhengjie.utils;


import java.util.regex.Pattern;

/**
 * Float工具类
 */
public class FloatUtil {

    /**
     * 判断一个字符串是否是float数的模板
     */
    private final static Pattern STR_FLOAT_PATTERN = Pattern.compile("^[-+]?[.\\d]*$");


    /**
     * @return 如果是浮点数则返回true，反之返回false
     */
    public static boolean isFloat(String target) {
    	if (target == null || target.isEmpty()) {
			return false;
		}
        return STR_FLOAT_PATTERN.matcher(target.trim()).matches();
    }
    
    public static Float valueOf(String str) {
        return valueOf(str, null);
    }

    public static Float valueOf(String str, Float defaultValue) {
        if (str == null || str.isEmpty()) {
            return defaultValue;
        }
        try {
			return Float.parseFloat(str);
		} catch (NumberFormatException e) {
			return defaultValue;
		}
    }
    
    public static String displayFloat(Float value) {
    	if (value == null) {
			return "";
		}
    	String text = String.valueOf(value);
    	if (text.endsWith(".0")) {
			return text.substring(0, text.length() - 2);
		}
    	return text;
    }
}
